package com.test.flink_sinks;

import com.test.beans.LogBean;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;

public class E01JdbcSink01 {
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port", 8888);
        StreamExecutionEnvironment webUI = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration);
        webUI.setParallelism(1);

        DataStreamSource<String> data = webUI.socketTextStream("127.0.0.1", 9001);
        // 数据转换成bean
        DataStream<LogBean> ds = data.map((MapFunction<String, LogBean>) line -> {
            // 数据在解析的时候可能会抛出异常 需要捕获异常防止程序停止  trycatch 快捷键 ctr+alt+t
            LogBean logBean = new LogBean();
            try {
                String[] arr = line.split(",");
                logBean.setName(String.valueOf(arr[0]));
                logBean.setLog(String.valueOf(arr[1]));
                logBean.setDesc(String.valueOf(arr[2]));
                logBean.setTimeStamp(Long.parseLong(arr[3]));
            } catch (Exception e) {

            }
            return logBean;
        });

        String sql = "insert into td_log (name, log, description, timestamp, create_time) values (?,?,?,?,?)";

        JdbcStatementBuilder<LogBean> statementBuilder = new JdbcStatementBuilder<LogBean>() {
            @Override
            public void accept(PreparedStatement preparedStatement, LogBean logBean) throws SQLException {
                preparedStatement.setString(1, logBean.getName());
                preparedStatement.setString(2, logBean.getLog());
                preparedStatement.setString(3, logBean.getDesc());
                preparedStatement.setLong(4, logBean.getTimeStamp());
                preparedStatement.setDate(5, new Date(Calendar.getInstance().getTime().getTime()));
            }
        };

        JdbcExecutionOptions executionOptions = JdbcExecutionOptions.builder()
                .withBatchIntervalMs(10000)
                .withBatchSize(10)
                .withMaxRetries(3)
                .build();

        JdbcConnectionOptions connectionOptions = new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                .withUrl("jdbc:mysql://127.0.0.1:3306/doe?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai")
                .withPassword("Sx123+654")
                .withUsername("root")
                .build();

        SinkFunction<LogBean> sink = JdbcSink.sink(sql, statementBuilder, executionOptions, connectionOptions);

        ds.addSink(sink);

        webUI.execute();
    }
}
